﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Cxuu.Web.Authorize;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin
{
    [Area("Admin")]
    [Authorize]
    public class StatementController : Base
    {
        private readonly LoginUtil _LoginUtil;
        private readonly ArticleStatementService _articleStatementService;
        private readonly ArticleCateService _articleCateService;
        private readonly ConfigService _configService;
        private readonly AttmentService _attment;
        private readonly LogService _logService;
        private readonly AdminUserService _adminUserService;
        public StatementController(LoginUtil LoginUtil, ArticleStatementService articleStatementService, ArticleCateService articleCateService,
            LogService logService, AttmentService attmentService, ConfigService configService, AdminUserService adminUserService)
        {
            _LoginUtil = LoginUtil;
            _articleStatementService = articleStatementService;
            _articleCateService = articleCateService;
            _configService = configService;
            _attment = attmentService;
            _logService = logService;
            _adminUserService = adminUserService;
        }

        /// <summary>
        ///  列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleStatement_Index)]
        public async Task<IActionResult> IndexAsync([FromQuery] ArticleStatementQuery query, int cid, int limit, int page = 1, int json = 0)
        {
            UserInfo adminUser = await _LoginUtil.UserInfoAsync();

            if (json == 1)
            {

                ArticleStatementQuery articleQuery = new()
                {
                    Cid = query.SearchCid ?? query.Cid,
                    CurrentPage = page,
                    Limit = limit,
                    Uid = adminUser.UserId,
                    Title = query.Title,
                    Clercator = query.Clercator,
                    StartDate = query.StartDate,
                    NickName = query.NickName,
                    EndDate = query.EndDate,
                    Uids = await _adminUserService.AdminPostAsUids(adminUser)
                };

                var pagedList = await _articleStatementService.GetListByCidAdminAsync(articleQuery);
                return Json(new { code = 0, count = pagedList.TotalItems, data = pagedList.Items });
            }
            ViewBag.cateInfo = await _articleCateService.GetInfo(cid);
            ViewBag.cid = query.Cid;
            ViewBag.catelist = await _articleCateService.CategoryListAsync(adminUser.DeptId, adminUser.Gid, (int)ModelTypeEnum.ModelType.工作报表);
            return View();

        }
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleStatement_AddOrEdit)]
        public async Task<IActionResult> AddOrEditAsync(int id, int edit = 0, int cid = 0, int preview = 0)
        {
            if (edit == 1)
            {
                EditArticleStatement data = await _articleStatementService.GetEditAsync(id);
                List<ViewAttment> attments = null;
                if (!string.IsNullOrEmpty(data.Attments))
                    attments = await _attment.GetListAsync(data.Attments);
                return Json(new { status = 1, data, attments });
            }
            //附件信息
            SytemConfig configSiteInfo = await _configService.GetByNameAsync();
            ViewBag.fileExts = configSiteInfo.FileExt;
            ViewBag.fileSize = configSiteInfo.FileSize;
            //栏目信息
            ArticleCate articleCate = await _articleCateService.GetInfo(cid);
            ViewBag.cateInfo = articleCate;
            ViewBag.id = id;//判断是否是编辑内容
            if (preview == 1) return View("Preview");
            else return View();

        }

        [HttpPost, ActionName("CreatePost")]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleStatement_AddOrEdit)]
        [Log(Name = "新增工作报表")]
        public async Task<IActionResult> CreatePostAsync(EditArticleStatement articlePost)
        {
            if (ModelState.IsValid)
            {
                UserInfo adminUser = await _LoginUtil.UserInfoAsync();

                ArticleStatement articleRes = new()
                {
                    Uid = adminUser.UserId,
                    ObjectId1 = articlePost.ObjectId1,
                    Title = articlePost.Title,
                    ObjectId2 = articlePost.ObjectId2,
                    Clercator = articlePost.Clercator,
                    Cid = articlePost.Cid,
                    Attments = articlePost.Attments,
                    Img = articlePost.Img,
                    Remarks = articlePost.Remarks,
                };

                ArticleStatement res = await _articleStatementService.InsertArticleAndContentAsync(articleRes);

                if (res.Id > 0)
                {
                    return Json(new { status = 1, msg = "新增工作报表 Id: " + articleRes.Id, cid = articleRes.Cid });
                }
                else
                    return Json(new { status = 0, msg = "新增失败！" });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { result = 0, msg = error });
            }
        }


        [HttpPost, ActionName("EditPost")]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleStatement_AddOrEdit)]
        [Log(Name = "修改工作报表")]
        public async Task<IActionResult> EditPostAsync(EditArticleStatement articlePost)
        {
            if (ModelState.IsValid)
            {
                int x = await _articleStatementService.UpdateArticleAndContentAsync(articlePost);
                if (x > 0)
                {
                    return Json(new { status = 1, msg = "修改工作报表 ID：" + articlePost.Id, cid = articlePost.Cid });
                }
                else
                {
                    return Json(new { status = 0, msg = "修改失败！" });
                }
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }


        [ActionPermissionFilter(Permission = PermissionKeys.ArticleStatement_Delete)]
        [Log(Name = "删除工作报表")]
        public async Task<IActionResult> Delete(int id)
        {
            if (await _articleStatementService.DelArticleAndContentAsync(id) > 0)
            {
                return Json(new { status = 1, msg = "删除工作报表 ID：" + id, url = "Statement/Index" });
            }
            else
                return Json(new { status = 0, msg = "删除失败！" });
        }
    }
}
